package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService{
    @Autowired
    private ITravelCommentRepository dao;
    @Autowired
    private MongoTemplate mongoTemplate;




    public Page<TravelComment> query(TravelCommentQuery qo) {
        //设置查询封装的对象
        Query query = new Query();

        //设置参数
        Criteria criteria =null;//条件分装对象
        if(qo.getTravelId() != -1){
            criteria = Criteria.where("travelId").is(qo.getTravelId());//等于
        }else {
            criteria = Criteria.where("travelId").ne(qo.getTravelId());//不等于
        }
        //添加查询条件
        query.addCriteria(criteria);

        //查询总条数
        long total = mongoTemplate.count(query, TravelComment.class);
        if(total == 0 ){
            return Page.empty();

        }
        //分页对象
        //参数1.这里当前页从0开始,参数2 每页3显示条数
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);
        //排序对象
        //参数1.表示排序规则 desc 参数2 排序的字段
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(sort);

        //查询所有记录 数
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return new PageImpl<TravelComment>(list, pageable, total);


    }


    /**
     * 保存评论操作
     * @param comment
     */
    public TravelComment save(TravelComment comment) {
        if(comment.getId() == null ){

            comment.setCreateTime(new Date());
        }
        if(comment.getRefComment()!=null && StringUtils.hasLength(comment.getRefComment().getId()) ){
            comment.setRefComment(this.get(comment.getRefComment().getId()));
        }
        dao.save(comment);
        //因为服务和服务之间
        return comment;
    }
    public TravelComment get(String id){
        return dao.findById(id).get();
    }


}
